import { setToken, clearToken } from '@/utils/auth'

import { loginApi, getUserInfoApi } from '@/api/user'

// 登录
export const login = (mobile, code) => {
    return async dispatch => {
        const res = await loginApi(mobile, code)
        setToken(res.token)
        dispatch({
            type: 'user/setToken',
            payload: res.token
        })
        return res
    }
}

// 获取用户信息
export const getUserInfo = () => {
    return async dispatch => {
        try {
            const res = await getUserInfoApi()
            dispatch({
                type: 'user/setName',
                payload: res?.name
            })
        } catch (error) {
            console.log(error);
        }
    }
}

// 退出登录
export const logout = () => {
    return dispatch => {
        clearToken()
        dispatch({ type: 'user/setToken', payload: '' })
        dispatch({ type: 'user/setName', payload: '' })
    }
}